<?php
declare (strict_types = 1);

namespace app;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Exception;
use think\Response;
use think\App;
use think\exception\ValidateException;
use think\Validate;


/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {}

    const SUCCESS = 200;        //成功
    const SERVER_ERROR = 500;   //服务器端失败
    const USER_ERROR = 501;     //用户端错误
    const NOT_LOGGED = 502;     //未登录

    /**
     * @param $code         状态码
     * @param $msg          返回信息
     * @param array $data   返回数据
     * @return mixed
     */
    public function returnJson($code,$msg,$data = []){
        $result = [
            'code'  => $code,
            'msg'   => $msg,
            'data'  => $data
        ];
        return Response::create($result,'json');
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    /**
     * 生成标签
     * @param $uid
     * @return string
     */
    function signToken($uid){
        $key='bigdataenv';
        $token=array(
            "iss"=>$key,        //签发者，可以为空
            "aud"=>'id',
            "iat"=>time(),      //签发对象
            "nbf"=>time()+24*60*60,   //token 过期时间
            "data"=>[
                'id'=>$uid,
        ]
        );
        $jwt = JWT::encode($token,$key,"HS256");   //生成了token
        return $jwt;
    }


    /**
     * 验证Token
     * @param $token
     * @return array
     */
    function checkToken($token){
        $key='bigdataenv';
        $res['status'] = false;
        try {
            JWT::$leeway        =   60;
            $decoded            =   JWT::decode($token,new Key($key,'HS256'));
            $arr                =   (array)$decoded;
            $res['status']      =   200;
            $res['data']        =   (array)$arr['data'];
            return $res;
        }catch (\Firebase\JWT\SignatureInvalidException $e){
            $res['info']    =   "签名不正确";
            return $res;
        }catch (\Firebase\JWT\BeforeValidException $e){
            $res['info']    =   "token失效";
            return $res;
        }catch (\Firebase\JWT\ExpiredException $e){
            $res['info']    =   "token过期";
            return $res;
        }catch (\Exception $e){
            $res ['info']   =   "未知错误";
            return $res;
        }
    }
}